package top.conangao.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.conangao.common.entity.ResponseResult;
import top.conangao.common.security.util.SecurityUtils;
import top.conangao.system.assemble.SysUserAssemble;
import top.conangao.system.domain.SysUser;
import top.conangao.system.domain.valid.UserValid;
import top.conangao.system.domain.vo.SysUserVO;
import top.conangao.system.service.SysUserService;

/**
 * @author ConanGao
 * @since 1.0
 **/
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class SysUserController {
    private final SysUserAssemble sysUserAssemble;
    private final SysUserService sysUserService;
    private final PasswordEncoder passwordEncoder;
    
    @GetMapping("/info")
    @Operation(summary = "用户管理")
    public ResponseResult<Object> userInfo(){
        Long id = SecurityUtils.currentUser().getId();
        return ResponseResult.ok("获取当前用户信息成功", sysUserAssemble.do2vo(sysUserService.getById(id)));
    }

    @GetMapping("/{id}/info")
    public ResponseResult<SysUserVO> getUser(@PathVariable("id") Long id) {
        return ResponseResult.ok("获取单个用户信息成功", sysUserAssemble.do2vo(sysUserService.getById(id)));
    }

    @GetMapping("/list")
    @PreAuthorize("hasRole('admin')")
    public ResponseResult<Page<SysUserVO>> pageUsers(Page<SysUser> page) {
        return ResponseResult.ok("查询用户信息列表成功",
                sysUserAssemble.do2vo(sysUserService.page(page, Wrappers.emptyWrapper())));
    }

    @PostMapping
    public ResponseResult<Void> saveUser(@Validated(UserValid.Add.class) @RequestBody SysUser sysUser) {
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUserService.save(sysUser);
        return ResponseResult.ok("添加用户信息成功");
    }
    
    @PutMapping
    public ResponseResult<Void> updateUser(@Validated(UserValid.Update.class) @RequestBody SysUser sysUser){
        if (StringUtils.hasText(sysUser.getPassword())){
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        }
        sysUserService.updateById(sysUser);
        return ResponseResult.ok("修改用户信息成功");
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Void> removeUser(@PathVariable("id")Long id){
        return sysUserService.removeById(id)?ResponseResult.ok("删除用户信息成功"):ResponseResult.fail("没有该用户");
    }
}
